package cn.edu.nsmc.modules.sys.service.impl;

import cn.edu.nsmc.common.utils.PageUtils;
import cn.edu.nsmc.common.utils.Query;
import cn.edu.nsmc.modules.sys.dao.SysWorksheetTypeDao;
import cn.edu.nsmc.modules.sys.entity.SysWorksheetType;
import cn.edu.nsmc.modules.sys.entity.vo.WorksheetTypeVO;
import cn.edu.nsmc.modules.sys.service.SysWorksheetTemplateService;
import cn.edu.nsmc.modules.sys.service.SysWorksheetTypeService;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("sysWorksheetTypeService")
public class SysWorksheetTypeServiceImpl extends ServiceImpl<SysWorksheetTypeDao, SysWorksheetType> implements SysWorksheetTypeService {

    @Autowired
    private SysWorksheetTemplateService sysWorksheetTemplateService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysWorksheetType> page = this.page(
                new Query<SysWorksheetType>().getPage(params),
                new QueryWrapper<SysWorksheetType>()
        );

        return new PageUtils(page);
    }

    @Override
    public ArrayList<WorksheetTypeVO> tree() {
        ArrayList<WorksheetTypeVO> res = new ArrayList<>();

        List<SysWorksheetType> parentList = list(new LambdaQueryWrapper<SysWorksheetType>()
                .eq(SysWorksheetType::getPid, -1).eq(SysWorksheetType::getIsDel,0));

        for (SysWorksheetType item : parentList) {
            WorksheetTypeVO parent = new WorksheetTypeVO();
            BeanUtil.copyProperties(item, parent);

            List<SysWorksheetType> childList = list(new LambdaQueryWrapper<SysWorksheetType>()
                    .eq(SysWorksheetType::getPid, item.getId()).eq(SysWorksheetType::getIsDel,0));
            List<WorksheetTypeVO> child = new ArrayList<>();

            for (SysWorksheetType c : childList) {
                WorksheetTypeVO vo = new WorksheetTypeVO();
                BeanUtil.copyProperties(c, vo);

                vo.setTemplate(sysWorksheetTemplateService.getById(vo.getTemplateId()));

                child.add(vo);
            }

            parent.setChildren(child);
            res.add(parent);
        }
        return res;
    }

}